package com.scwatch.core.fulltext;

import com.scwatch.common.fulltext.LuceneIndexTemplate;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.Node;
import com.scwatch.core.domain.Task;
import com.scwatch.core.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class NodeFulltextGeneratorImpl implements NodeFulltextGenerator {
	private final Logger logger = LoggerFactory
			.getLogger(NodeFulltextGeneratorImpl.class);

	public void addDocument(final Node[] beans) {
		new Thread() {
			@Override
			public void run() {
				try {
					// 等待主线程结束，提交事务后，再运行。
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					logger.error(null, e);
				}
				for (Node bean : beans) {
				    if(bean!=null && bean.getNodeModel().getFlag()!=null
                            && Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS.equals(bean.getNodeModel().getFlag())){
                        nodeFulltextService.addDocument(bean.getId());
                    }
				}
			}
		}.start();
	}

	public void updateDocument(final Node[] beans) {
		new Thread() {
			@Override
			public void run() {
				try {
					// 等待主线程结束，提交事务后，再运行。
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					logger.error(null, e);
				}
				for (Node bean : beans) {
                    if(bean!=null && bean.getNodeModel().getFlag()!=null
                            && Constants.MODEL_FLAG_ANCHOR_LOOP_DYNAMICS.equals(bean.getNodeModel().getFlag())){
                        nodeFulltextService.updateDocument(bean.getId());
                    }
				}
			}
		}.start();
	}

	public void deleteDocuments(final Node[] beans) {
		for (Node bean : beans) {
			template.deleteDocuments(FNode.id(bean.getId()));
		}
	}

	public void addDocument(final Integer siteId, final Node parent,
			Integer userId) {
		String name = "ALL";
		if (parent != null) {
			name = parent.getName();
		}
		Task task = taskService.save("parent Node: " + name, null, Task.FULLTEXT,
				userId, siteId);
		final Integer taskId = task.getId();
		new Thread() {
			@Override
			public void run() {
				try {
					nodeFulltextService.addDocument(siteId, parent, taskService,
							taskId);
					taskService.finish(taskId);
				} catch (Exception e) {
					taskService.abort(taskId);
					logger.error("create parent node fulltext index error!", e);
				}
			}
		}.start();
	}

	private TaskService taskService;
	private NodeFulltextService nodeFulltextService;
	private LuceneIndexTemplate template;

	@Autowired
	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	@Autowired  
    public void setNodeFulltextService(NodeFulltextService nodeFulltextService) {
        this.nodeFulltextService = nodeFulltextService;
    }

	@Autowired
	public void setLuceneIndexTemplate(LuceneIndexTemplate template) {
		this.template = template;
	}
}
